import {
	AppCounterHelperBase,
	IAppCounterHelper,
	IContext,
	IParam,
} from '@/core';

export class AppCounterHelper
	extends AppCounterHelperBase
	implements IAppCounterHelper
{
	/**
	 * 单例服务
	 *
	 * @protected
	 * @static
	 * @type {IAppCounterHelper}
	 * @memberof AppCounterHelper
	 */
	private static service: IAppCounterHelper;

	/**
	 * 获取实例
	 *
	 * @static
	 * @return {*}  {IAppCounterHelper}
	 * @memberof AppCounterHelper
	 */
	static getInstance(): IAppCounterHelper {
		if (!this.service) {
			this.service = new AppCounterHelper();
		}
		return this.service;
	}

	/**
	 * 计数器Map
	 *
	 * @static
	 * @memberof AppCounterHelper
	 */
	private static counterServiceMap = new Map();

	/**
	 * 获取计数器数据
	 *
	 * @memberof AppCounterHelper
	 */
	public async getCounterItems(
		tag: string,
		context: IContext,
		viewParams: IParam,
		cb: Function
	) {
		//  根据tag 获取计数器标识
		const counter = App.getAppCounterConfig()[tag];
		if (!counter) return;

		let counterService = AppCounterHelper.counterServiceMap.get(tag);
		if (!counterService) {
			AppCounterHelper.counterServiceMap.set(tag, {
				codeName: counter.codeName,
				delayTime: counter.timer ? counter.timer : 6000,
				timer: null,
				getAction: counter.getAction,
				appDeCodeName: counter.appDeCodeName,
				counterData: {},
			});
			counterService = AppCounterHelper.counterServiceMap.get(tag);
		}
		await this.executeRefreshData(tag, context, viewParams, cb);
	}

	/**
	 * 执行刷新数据
	 *
	 * @memberof  AppCounterHelper
	 */
	public async executeRefreshData(
		tag: string,
		context: IContext,
		viewParams: IParam,
		cb: Function
	) {
		const counterService = AppCounterHelper.counterServiceMap.get(tag);
		await this.fetchCounterData(counterService, context, viewParams, cb);
		this.destroyCounter(tag);
		counterService.timer = setInterval(() => {
			this.fetchCounterData(counterService, context, viewParams, cb);
		}, counterService.delayTime);
	}

	/**
	 * 获取计数器数据
	 *
	 * @memberof  CounterService
	 */
	public async fetchCounterData(
		counterService: any,
		context: IContext,
		viewParams: IParam,
		cb: Function
	) {
		if (counterService.appDeCodeName && counterService.getAction) {
			try {
				const dataService = await App.getDataService(
					counterService.appDeCodeName,
					context
				);
				const response = await dataService[counterService.getAction](
					context,
					viewParams,
					false
				);
				const { status, data } = response;
				if (status == 200) {
					counterService.counterData = data;
					cb(counterService.counterData);
				} else {
					console.error(' 获取计数器数据异常[网络请求异常]');
				}
			} catch (error: any) {
				console.error(error);
			}
		}
	}

	/**
	 * 销毁计数器
	 *
	 * @memberof CounterServiceBase
	 */
	public destroyCounter(tag: string) {
		const counterService = AppCounterHelper.counterServiceMap.get(tag);
		if (counterService && counterService.timer) {
			clearInterval(counterService.timer);
		    counterService.timer = null;
        }
	}
}
